package com.doliere.android.app.p2p.threads;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Enumeration;
import java.util.Hashtable;

import android.annotation.SuppressLint;
import android.net.wifi.p2p.WifiP2pInfo;
import android.os.AsyncTask;

/**
 * 
 * @author doliere
 * This class is reponsible for issuing a outgoing to device which is a groupowner.
 * When the connection is established, return the socket that has been created.
 */
public class P2pClientSocket extends AsyncTask<Hashtable<String, WifiP2pInfo>, String, Socket>{
	
	private Socket mClient;
	private int mPort;
	private String mMacAddress;
	
	public P2pClientSocket(int port, String macAdress){
		mPort = port;
		mMacAddress = macAdress;
		mClient = new Socket();
	}

	@SuppressLint("NewApi")
	@Override
	protected Socket doInBackground(Hashtable<String, WifiP2pInfo>... params) {
		Enumeration<String> adr = params[0].keys();
		String ad = adr.nextElement();
		WifiP2pInfo infos = params[0].get(ad);
		try {
			mClient.bind(null);
			mClient.connect(new InetSocketAddress(infos.groupOwnerAddress, mPort));
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		publishProgress("CONNECTION ESTABLISHED WITH " + mMacAddress);
		
		return mClient;
	}
}
